  var app = getApp();
  import api from '../../utils/api.js'
  import {
      showLoading,
      hideLoading
  } from '../../utils/util.js'
  import {
      HTTP
  } from '../../utils/http.js'
  import { config } from '../../utils/config'
  let http = new HTTP()
  let sign = true; // 时间的标志

  Page({
      data: {
          // 此页面 页面内容距最顶部的距离
          height: app.globalData.height * 2 + 20,
          list: [],
          num: 0,
          showModal: false, //收货方式model
          showModal1: false, //送达时间model
          status: 0, //快递配送 1， 到店自取 0
          deliveryDay: null, // 今天 0 ，明天 1
          data2: 0, // 选择的确定时间段
          show: false, // 是否展示 deliveryDay， data2
          time1: [], // 今天的时间段 现在不展示
          time2: [], // 明天的时间段
          today: {},
          beizhu: "",
          dizhi: "",
          address: "", //用户地址
          shopAddress: "", //店铺地址
          myCook: [], //菜谱的单品
          selectMenus: [], //选择的菜谱
          yuding: {}, //商家是否支持预定优惠
          mark: true,
          showModel: false, //结算 按钮的模态窗口
          yh: [], //商家原始设置的优惠
          filterYh: [], //过滤 所有最大力度的优惠
          totalMoneyInit: 0, //初始总价，没有计算任何优惠的
          totalMoney: 0,
          specialMoney: 0, // 以优惠多少钱
          recommendSelectedItem: [],
          imgUrl: config.imgUrl,
      },

      submit() {
          this.setData({
              showModal: true
          })
      },
      time() {
          var time = new Date();
          var data = time.getDate();
          var hours = time.getHours();
          var min = time.getMinutes();
          var today = {};
          today.data = data;
          today.hours = hours;
          today.min = min;
          this.setData({
              today,
              showModal1: true //弹出 选择送达时间的模态框
          });
          http.request({
              url: api.getTime,
              method: "POST",
              success: res => {
                  var time = res.data;
                  var time1 = [];
                  var min = this.data.today.min;
                  console.log(data)
                  if (min < 10) {
                      min = "0" + min;
                  }
                  var today = this.data.today.hours.toString() + min;
                  for (var i in time) {
                      var item1 = time[i].split("-")[0].split(":")[0];
                      var item2 = time[i].split("-")[0].split(":")[1];
                      var item = item1 + item2;
                      if (item - today > 0) {
                          time1.push(time[i]);
                      }
                  }

                  // //即今天的时间段为空时：
                  // if (time1.length == 0) {
                  //   this.setData({
                  //     deliveryDay: 1
                  //   });
                  // }

                  this.setData({
                      time2: res.data,
                      time1,
                      deliveryDay: 1
                  });
              }
          });
      },
      beizhu(e) {
          this.setData({
              beizhu: e.detail.value
          })
      },
      xiugai() {
          var dizhi = wx.getStorageSync("address")
          dizhi = JSON.stringify(dizhi)
          wx.navigateTo({
              url: "/pages/changeDizhi/changeDizhi?dizhi=" + dizhi + "&status=1",
          })
      },
      wanshan() {
          wx.navigateTo({
              url: "/pages/wanshanDizhi/wanshanDizhi"
          })
      },
      toNum() {
          wx.navigateTo({
              url: '/pages/num/num?type=' + this.data.type,
          })
      },
      xuanze1(e) {
          let timeNum = e.currentTarget.dataset.time; // 提取时间，是否是明天 是1 ，预定
          //当今天的时间段为空时，即只能预定了
          let time1 = this.data.time1;
          if (time1.length == 0) {
              return;
          } else {
              this.setData({
                  deliveryDay: timeNum
              });
          }
          //若用户重选时间段，则覆盖
          wx.setStorageSync("timeField1", e.currentTarget.dataset.time);
      },
      xuanze2(e) {
          let filterYh = this.data.filterYh; // 过滤好的 优惠政策
          let totalMoneyInit = this.data.totalMoneyInit;
          let deliveryDay = e.currentTarget.dataset.day;

          this.setData({
              data2: e.currentTarget.dataset.time,
              showModal1: false,
              show: true,
              deliveryDay
          });
          this.getMoneyChange(filterYh, totalMoneyInit);
          //若用户重选时间段，则覆盖
          wx.setStorageSync("timeField2", e.currentTarget.dataset.time);
          if (!wx.getStorageSync("timeField1")) {
              wx.setStorageSync("timeField1", 0);
          }
      },
      changeA(e) {
          // 快递配送 status === 1 ,满包邮——discounts这个字段变成了true，不是number了
          console.log("快递配送", e);
          let status = e.currentTarget.dataset.status;
          let filterYh = this.data.filterYh; //优惠政策
          let totalMoneyInit = this.data.totalMoneyInit;

          this.setData({
              status,
              showModal: false
          });
          this.getMoneyChange(filterYh, totalMoneyInit);
      },
      changeB(e) {
          // 自行提取 status  === 0
          console.log("自提方式", e);
          let status = e.currentTarget.dataset.status;
          let filterYh = this.data.filterYh; // 过滤好的 优惠政策
          let totalMoneyInit = this.data.totalMoneyInit;

          this.setData({
              status,
              showModal: false
          });
          this.getMoneyChange(filterYh, totalMoneyInit);
      },
      close: function() {
          this.setData({
              showModal: false,
              showModal1: false
          })
      },
      //提交订单时，送达时间的缓存
      timeFieldStorage() {
          let timeField1 = wx.getStorageSync('timeField1') // 0 今天  1明天
          let timeField2 = wx.getStorageSync('timeField2') // 时间段

          if (timeField1 && timeField2) {
              this.setData({
                  deliveryDay: timeField1,
                  data2: timeField2,
                  showModal1: false,
                  show: true
              })
          }
      },
      onLoad: function(options) {
          // 获得city_id
          if (wx.getStorageSync('user_id')) {
              let obj = {
                  id: wx.getStorageSync("user_id"),
                  name: wx.getStorageSync("city_name")
              }
              http.request({
                  url: api.getAddUserCityId,
                  data: obj,
                  success: res => {
                      wx.setStorageSync("city_id", res.data.id);
                  }
              })
          }



          console.log('options111111111111', options)
          let shopId = options.shopId;
          let shopAddress = options.shopAddress;
          if (shopAddress) {
              this.setData({
                  shopAddress,
                  shopId
              })
          }

          //获取地址
          http.request({
                  url: api.oneAddress,
                  method: "POST",
                  data: {
                      user_id: wx.getStorageSync("user_id")
                  },
                  success: (res) => {
                      console.log("地址！！！！！！", res)
                      this.setData({
                          dizhi: res.data
                      })
                  }
              })
              // 获取 选择的 菜谱
          this.getSelectMenus();

          //////////////////////////////////////////
          //正常的 从菜谱菜篮 ——进入
          if (options.menuType == 1) {
              console.log('options.menuType', options.menuType)
              let myCook = wx.getStorageSync("myCook")
              let userMenus = wx.getStorageSync('userMenus')
              let recommendSelectedItem = wx.getStorageSync('recommendSelectedItem')
              if (userMenus && recommendSelectedItem) {
                  this.setData({
                      myCook,
                      userMenus,
                      recommendSelectedItem,
                      shopId: options.shopId,
                      menuType: options.menuType
                  })
              }

              // 获取 当前店铺的信息-优惠政策
              let singleShopList = wx.getStorageSync('singleShopList')
              console.log(singleShopList)
              if (singleShopList) {

                  this.setData({
                      singleShopList
                  })

                  //状态 0正常 1删除
                  //优惠类型 1满减价格，2满送商品，3满免配送费，4预定优惠，5自提优惠
                  let yh = singleShopList.yh;
                  if (yh.length == 0) {
                      console.log('商家没有设置优惠！！！')
                      this.initTotalMoney(options);
                      return false;
                  } else {
                      yh = yh.filter((ele) => { // 商家是否开启优惠
                              return ele.status == 0
                          })
                          //判断 商家 是否支持预定优惠
                      let yuding = {
                          booking: false,
                          num: 0,
                          condition: 0
                      };
                      yh.forEach((ele) => {
                          if (ele.pon.type == 4) {
                              yuding.booking = true
                              yuding.num = Number(ele.discounts)
                              yuding.condition = ele.condition
                          }
                      })
                      this.setData({
                          yh,
                          yuding
                      })
                      this.initTotalMoney(options);
                  }

              }


          } else if (options.againType == 1) { //从再来一单按钮进入——提交订单页面
              this.setData({
                  againType: true,
              })
              this.showContentAgain();
          }

      },
      //初始化页面时，总价 与 优惠价格 的 初始化
      initTotalMoney(options) {
          // let singleShopList = wx.getStorageSync("singleShopList");
          // let oneShopInfo = wx.getStorageSync('oneShopInfo');
          // let shipping_fee = Number(singleShopList.shipping_fee);
          let totalMoneyInit = Number(options.totalMoney); // 初始价格
          //判断商家是否开启配送is_delivery：0关闭 1开启
          //默认，自取，不计算配送费
          // 计算符合商家优惠条件后的总价
          let yh = singleShopList.yh;
          this.getTotalPrice(totalMoneyInit, yh);
          this.setData({
              totalMoneyInit,
              shopId: options.shopId
          });


          // //需要多次循环支付时，使用送达时间的缓存
          // this.timeFieldStorage();
          // let deliveryDay = this.data.deliveryDay; // 等于 1 是明天配送
          // let status = this.data.status;
          // if (deliveryDay === 1) {
          //   // 提取时间，是否是明天 是1 ，预定
          //   let filterYh = this.data.filterYh; //优惠政策
          //   let totalMoney = this.data.totalMoney;
          //   let alreadyMoney = this.data.alreadyMoney;
          //   let totalMoneyInit = this.data.totalMoneyInit;
          //   if (filterYh) {
          //     filterYh.forEach((ele, index) => {
          //       if (ele.pon.type == 4 && totalMoneyInit >= ele.condition) { //4 预定优惠
          //         totalMoney = totalMoney - Number(ele.discounts)
          //         alreadyMoney += Number(ele.discounts)
          //         ele.mark = true
          //       }
          //     })
          //   }
          //   this.setData({
          //     totalMoney,
          //     alreadyMoney,
          //     filterYh
          //   })
          // }

      },
      // 计算满足优惠条件的总价，与不满足时
      // getTotalPrice(initMoney, yh) {
      //   let filterYh = []; //展示所有符合最高力度的优惠条件
      //   let notYh = []; //展示未满足 - 更多优惠
      //   let status = this.data.status;
      //   let singleShopList = this.data.singleShopList;

      //   if (yh) {
      //     console.log('优惠计算', yh)
      //     //要满足 店铺开启配送， 设置了 配送费
      //     if (singleShopList.is_delivery === 1) {
      //       yh.forEach((ele) => {
      //         if (ele.pon.type == 3) {
      //           if (initMoney >= ele.condition) {
      //             filterYh.push(ele)
      //             ele.freeFee = true // 新建一个,满足，没有配送费
      //             ele.shipping_fee = 0
      //           } else {
      //             filterYh.push(ele)
      //             ele.freeFee = false
      //             ele.shipping_fee = singleShopList.shipping_fee
      //           }
      //         }
      //       })
      //     }



      //     let arr1 = [];
      //     //取最大的满减
      //     yh.forEach((ele, index) => {
      //       if (ele.pon.type == 1) {
      //         //满减,拿到 符合满减的条件
      //         if (initMoney >= ele.condition) {
      //           ele.myIndex = index;
      //           arr1.push(ele);
      //         } else {
      //           notYh.push(ele);

      //         }
      //       }
      //     });
      //     //拿到最大的满减力度,其在当前yh下的索引
      //     let maxFullMinus = this.getmaxCondition(arr1);
      //     console.log("拿到最大的满减力度", maxFullMinus);
      //     if (maxFullMinus != null || maxFullMinus != undefined) {
      //       filterYh.push(maxFullMinus);
      //     }

      //     let arr2 = [];
      //     //展示其最大的满送力度
      //     yh.forEach((ele, index) => {
      //       if (ele.pon.type == 2) {
      //         // 满送食材
      //         if (initMoney >= ele.condition) {
      //           ele.myIndex = index;
      //           ele.mark = true;
      //           arr2.push(ele);
      //         } else {
      //           notYh.push(ele);
      //         }
      //       }
      //     });
      //     //拿到最大的满送力度,其在当前yh下的索引
      //     let maxFullSend = this.getmaxCondition(arr2);
      //     console.log("拿到最大的满送力度", maxFullSend);
      //     if (maxFullSend != null || maxFullSend != undefined) {
      //       filterYh.push(maxFullSend);
      //     }

      //     let arr4 = [];
      //     //展示其最大的预定优惠力度
      //     yh.forEach((ele, index) => {
      //       if (ele.pon.type == 4) {
      //         if (initMoney >= ele.condition) {
      //           ele.myIndex = index;
      //           arr4.push(ele);
      //         } else {
      //           notYh.push(ele);
      //         }
      //       }
      //     });
      //     let maxFullBook = this.getmaxCondition(arr4);
      //     console.log("拿到最大的预定优惠力度", maxFullBook);
      //     if (maxFullBook != null || maxFullBook != undefined) {
      //       filterYh.push(maxFullBook);
      //     }

      //     let arr5 = [];
      //     //展示其最大的自提优惠力度
      //     yh.forEach((ele, index) => {
      //       if (ele.pon.type == 5) {
      //         if (initMoney >= ele.condition) {
      //           ele.myIndex = index;
      //           arr5.push(ele);
      //         } else {
      //           notYh.push(ele);
      //         }
      //       }
      //     });
      //     let maxFullPickUp = this.getmaxCondition(arr5);
      //     console.log("拿到最大的自提优惠力度", maxFullPickUp);
      //     if (maxFullPickUp != null || maxFullPickUp != undefined) {
      //       filterYh.push(maxFullPickUp);
      //     }
      //     this.getMoneyChange(filterYh, initMoney);
      //     this.setData({
      //       yh,
      //       notYh,
      //       filterYh
      //     });
      //   }
      // },
      //返回符合条件的最大值
      maxNum(args) {
          return Math.max.apply(null, args);
      },
      getmaxCondition(arr) {
          // let ret = []
          // arrayobj.forEach( (ele,index) => {
          //   ret.push(Number(ele.condition))
          // })
          // let maxi = 0;
          // let max = Math.max.apply(null, ret);

          let maxVal = arr[0];
          for (let i of arr) {
              maxVal = Number(maxVal.condition) > Number(i.condition) ? maxVal : i;
          }
          return maxVal
      },
      //变更取货方式以及 取货时间时的价格变化
      //ele.pon.type 优惠类型 1满减价格，2满送商品，3满免配送费，4预定优惠，5自提优惠
      getMoneyChange(filterYh, totalMoneyInit) {
          let specialMoney = 0;
          let moneyIng = totalMoneyInit;
          let status = this.data.status;
          let deliveryDay = this.data.deliveryDay;
          console.log('moneyIng', moneyIng)
          filterYh.forEach((ele) => {
              if (ele.pon.type === 1) {
                  moneyIng = moneyIng - Number(ele.discounts);
                  specialMoney += Number(ele.discounts);
              } else if (ele.pon.type === 2) {
                  //满送商品
              } else if (ele.pon.type === 3 && status == 1) {
                  //满免配送费,不计入 优惠价格内
                  if (ele.freeFee == false) {
                      moneyIng = moneyIng + Number(ele.shipping_fee);
                  }
              } else if (ele.pon.type === 4 && deliveryDay == 1) { // 预定明天的优惠
                  moneyIng = moneyIng - Number(ele.discounts);
                  specialMoney += Number(ele.discounts);
              } else if (ele.pon.type === 5 && status == 0) { // status：0 自提优惠，1 配送
                  moneyIng = moneyIng - Number(ele.discounts);
                  specialMoney += Number(ele.discounts);
              }
          })

          this.setData({
              specialMoney,
              totalMoney: moneyIng
          })
      },



      //获取菜谱
      getSelectMenus() {
          let selectMenus = wx.getStorageSync('userMenus')
          this.setData({
              selectMenus: selectMenus
          })
      },
      // // 下单时，符合的促销优惠
      // coupon_json() {
      //   let coupon_json = [];
      //   let filterYh = this.data.filterYh;
      //   if (filterYh) {
      //     //商家如有设置优惠政策时
      //     //循环符合优惠的 标签
      //     filterYh.forEach((ele, index) => {
      //       let ret = {};
      //       ret.condition = ele.condition;
      //       ret.discounts = ele.discounts;
      //       ret.name = ele.pon.name;
      //       ret.type = ele.pon.type;
      //       // 总价满足 商家设置的满足条件时，才加上
      //       if (ele.pon.type == 3) {
      //         ret.shipping_fee = ele.shipping_fee
      //       }
      //       if (ele.pon.type == 2) {
      //         ret.product_name = ele.product_name;

      //       }
      //       coupon_json[index] = ret;

      //     });
      //     // 过滤
      //     coupon_json = coupon_json.filter(ele => {
      //       if (ele != undefined || ele != null) {
      //         return true;
      //       }
      //     });
      //   }

      //   // let status = this.data.status;
      //   //若果店铺没有设置 满多免配送费，type=3,且设置了 配送费，就要把配送费传过去
      //   let singleShopList = this.data.singleShopList;
      //   let shop_fee = singleShopList.shipping_fee
      //   coupon_json.push({
      //     type: 6,
      //     name: "配送费",
      //     fee: shop_fee
      //   })
      //   return coupon_json;
      // },


      // 从 再来一单 进入 页面，展示内容(菜谱的)
      showContentAgain() {
          let totalMoneyInit = 0;
          let oneShopInfo = wx.getStorageSync('oneShopInfo');
          let againOrderItem = wx.getStorageSync('againOrderItem');

          let shop_id = againOrderItem.shop_id; //店铺id
          let ids = []; // 单品 id 
          let snap_items = againOrderItem.snap_items; //对象

          let againMenus = [] // 菜谱
          let recommendSelectedItem = [] //菜谱里的食材
          for (let i in snap_items) {
              againMenus.push(snap_items[i].cook_book_name)
          }
          console.log('againMenus', againMenus)
          this.setData({
              againMenus,
              shopAddress: againOrderItem.address || againOrderItem.shops.address
          })

          //验证 初始价格
          for (let i in snap_items) {
              for (let j in snap_items[i].product_id) {
                  console.log(snap_items[i].product_id[j])
                  recommendSelectedItem.push(snap_items[i].product_id[j])
              }
          }
          console.log('recommendSelectedItem', recommendSelectedItem)
          recommendSelectedItem.forEach((ele) => {
              ids.push(ele.id)
          })
          let idsString = ids.join()
          console.log('ids', idsString);

          this.tryAgainVerifyPrice(shop_id, idsString).then((remoteData) => {
              // 先取差集 ，在验证价格是否相等
              let ret = [];
              recommendSelectedItem.forEach((ele, index) => {
                      remoteData.forEach((rEle, rIndex) => {
                          if (rEle.product_id === ele.id) {
                              ele.price = Number(rEle.price)
                              ret.push(ele)
                          }
                      })
                  })
                  //验证过后 重新计算初始价格,ret为当前可售卖的单品，未考虑ret为[]时；
              console.log('rrrrrr', ret);
              ret.forEach((ele) => {
                  totalMoneyInit += ele.price;
              })

              let totalMoney = this.getTotalPrice(totalMoneyInit, oneShopInfo.yh) //优惠后的 总价

              this.setData({
                  recommendSelectedItem: ret,
                  totalMoneyInit, // 验证过价格后，所有单品食材的总价，不变的
                  totalMoney
              })
          })

      },
      // 再来一单商品验证库存价格, 后端做了验证库存的判断
      //若单品 没有，则不会返回
      tryAgainVerifyPrice(shop_id, ids) {
          let that = this;
          return new Promise(function(resolve, reject) {
              http.request({
                  url: api.tryAgain,
                  method: "POST",
                  data: {
                      id: shop_id,
                      ids: ids
                  },
                  success: (res) => {
                      console.log('res', res)
                      if (res.code == 200) {
                          let data = res.data;
                          let existID = []; //验证通过的产品id
                          data.forEach((ele) => {
                              existID.push(ele.product_id)
                          })
                          that.setData({
                              existID
                          })
                          resolve(data);
                      } else if (res.data.error_code === 40003) {

                          console.log('验证不通过,该商家没有传入的任何商品')
                          that.setData({
                              shopDisabled: true
                          })
                      }

                  },
                  fail: (err) => {
                      console.log(err)
                  }
              })
          })

      },

      // 再来一单,菜谱的 提交按钮
      submitAgain() {
          let user_id = wx.getStorageSync("user_id");
          let existID = this.data.existID; //验证通过的id；
          let that = this;
          let againType = 1; //从 再来一单 进入
          let recommendSelectedItem = this.data.recommendSelectedItem; //店铺可售卖的单品
          let againOrderItem = wx.getStorageSync('againOrderItem');
          let snap_items = againOrderItem.snap_items; //对象

          let arr_snap_items = []; //数组
          for (let prop in snap_items) {
              arr_snap_items.push(snap_items[prop])
          }
          console.log('arr_snap_items', arr_snap_items)
          let news = {};
          let product_id = [];
          arr_snap_items.forEach((ele, index) => {
              for (let j in ele.product_id) {

                  existID.forEach((idEle) => {
                      if (ele.product_id[j].id == idEle) {
                          console.log('jjjjjjjjjjj', ele.product_id[j].id)
                          product_id.push(ele.product_id[j]);
                          console.log('product_id', product_id)
                          news[index] = {
                              cook_book_id: ele.cook_book_id,
                              cook_book_name: ele.cook_book_name,
                              product_id: product_id
                          }
                      }

                  })

              }
              product_id = []
          })


          console.log('news', news)
          console.log('arr_snap_items', arr_snap_items)

          let arrs = this.data.recommendSelectedItem;
          let v = {}

          //拿到 v参数：食材和对应的数量，必填
          //对象 循环 构造v参数
          arrs.forEach((ele, index) => {
              v[index] = {
                  product_id: ele.id,
                  num: ele.num
              }
          })
          console.log('vvvvvvvv', v)
              //走支付流程
          let num = 0
          if (this.data.status == 0) {
              if (this.data.data2 == 0) {
                  wx.showToast({
                      title: '请填写自提时间',
                      icon: 'none',
                      duration: 1500,
                      mask: true
                  })
              } else {
                  num++
              }
          } else {
              if (this.data.data2 == 0) {
                  wx.showToast({
                      title: '请填写送达时间',
                      icon: 'none',
                      duration: 1500,
                      mask: true
                  })
              } else {
                  num++
              }
          }

          var time = this.data.time2
          var get_time_id = 1
          for (var i in time) {
              if (time[i] == this.data.data2) {
                  get_time_id = i * 1
              }
          }

          if (!this.data.detail) {
              wx.showToast({
                  title: '请填写详细地址',
                  icon: 'none',
                  duration: 1500,
                  mask: true
              })

              return false;
          }
          // let coupon_json = this.coupon_json();
          let data = {
              snap_address: this.data.address + this.data.detail, //收货的全部地址，必填
              receiving_method: this.data.status, // 接受方式 0自提，1配送，默认为0
              user_id: user_id,
              get_time_id: get_time_id, //收货时间段id，必填
              totalPrice: this.data.totalMoney, //价格，单位为分，必填
              send_day: this.data.deliveryDay, // 	0今天，1明天 默认为0
              remark: this.data.beizhu, //备注
              shop_id: againOrderItem.shop_id, //商户id，必填
              snap_items: JSON.stringify(news), //订单中包含的菜谱，菜谱中包含的食材id和食材数量，必填
              v: JSON.stringify(v), //食材和对应的数量，必填
              mobile: this.data.dizhi.mobile,
              username: this.data.name,
              coupon_json: JSON.stringify(coupon_json) || [] // 优惠
          };
          console.log('1111111', data)

          if (num == 1) {
              this.setData({
                  showModel: true
              })
              showLoading('加载中...');
              http.request({
                  url: api.placeOrder,
                  data: data,
                  success: (res) => { //请求成功的回调

                      hideLoading();
                      let order_id = res.order_id;
                      if (res.code == 200) {
                          that.pay(order_id, user_id, againType)
                      }

                  }
              })
          }
      },


      // 正常提交订单单并支付
      submit_cook_book(e) {
          let user_id = wx.getStorageSync("user_id");
          let that = this;
          var v = {}, //参数v
              snap_items = {}, //参数snap_items
              ret = {}; //参数snap_items过渡对象
          var aaa = []; //参数snap_items过渡数组
          let myCook = this.data.myCook;
          let userMenus = this.data.userMenus;
          let recommendSelectedItem = this.data.recommendSelectedItem;
          let total_count = 0; //商品 总数
          console.log(recommendSelectedItem)
          console.log(userMenus)
          recommendSelectedItem.forEach(function(ele, index, arr) {
              // v[index + 1] = {
              //   product_id: ele.product_id,
              //   num: ele.num
              // }
              products[{ product_id: ele.product_id }]
              console.log(ele)
              total_count += ele.num
          })

          console.log('total_count', total_count, myCook)
              //遍历数据拿到接口参数所需的结构
          myCook.forEach((ele, index) => {
              ret[i] = {
                  id: ele.product_id,
                  price: Number(ele.price),
                  // num: ele.number,
                  name: ele.name,
                  unit: ele.summary, //出售计价单位
                  count: ele.count, //单品数量
                  main_img_url: ele.img,
                  unitZn: ele.unitZn || ''
              }
              aaa[index] = ret
              snap_items[index] = {
                  cook_book_id: ele.cook_id,
                  cook_book_name: ele.cook_name,
                  product_id: ret
              }
              ret = {}
          })

          let num = 0
          if (this.data.status == 0) {
              if (this.data.data2 == 0) {
                  wx.showToast({
                      title: '请填写自提时间',
                      icon: 'none',
                      duration: 1500,
                      mask: true
                  })
              } else {
                  num++
              }
          } else {
              if (this.data.data2 == 0) {
                  wx.showToast({
                      title: '请填写送达时间',
                      icon: 'none',
                      duration: 1500,
                      mask: true
                  })
              } else {
                  num++
              }
          }

          var time = this.data.time2
          var get_time_id = 1
          for (var i in time) {
              if (time[i] == this.data.data2) {
                  get_time_id = i * 1
              }
          }

          if (!this.data.detail) {
              wx.showToast({
                  title: '请填写详细地址',
                  icon: 'none',
                  duration: 1500,
                  mask: true
              })

              return false;
          }
          // let coupon_json = this.coupon_json();
          // console.log('coupon_json', coupon_json)

          let data = {
              snap_address: this.data.address + this.data.detail, //收货的全部地址，必填
              receiving_method: this.data.status, // 接受方式 0自提，1配送，默认为0
              // user_id: user_id,
              get_time_id: get_time_id, //收货时间段id，必填//价格，单位为分，必填
              totalPrice: this.data.totalMoney,
              total_count: total_count, //食材总数
              send_day: this.data.deliveryDay, // 	0今天，1明天 默认为1
              remark: this.data.beizhu, //备注
              shop_id: this.data.shopId, //商户id，必填
              snap_items: JSON.stringify(wx.getStorageSync('myCook')), //订单中包含的菜谱，菜谱中包含的食材id和食材数量，必填
              v: JSON.stringify(v), //食材和对应的数量，必填
              mobile: this.data.dizhi.mobile,
              count: this.data.count, //单品数量
              // username: this.data.name,
              // coupon_json: JSON.stringify(coupon_json) || [], // 优惠
              type: 1
          };
          //  data = JSON.stringify(data);
          // console.log('data,', data)
          if (num == 1) {
              this.setData({
                  showModel: true
              })
              console.log(data)
              showLoading('加载中...')
              http.request({
                  url: api.placeOrder,
                  data: {
                      products: [{
                          product_id: id,
                          count: count
                      }]
                  },
                  success: (res) => { //请求成功的回调
                      console.log('创建订单成功', res)
                      hideLoading();
                      let order_id = res.order_id;
                      if (res.code == 200) {
                          that.pay(order_id, user_id)
                      } else {
                          wx.showToast({
                              title: '验证错误',
                              icon: 'none',
                              duration: 1500,
                          })
                          this.setData({
                                  showModel: false
                              })
                              // setTimeout( ()=> {
                              //   wx.redirectTo({
                              //     url: '/pages/my/my'
                              //   })
                              // })
                      }
                  }
              })
          }

      },
      /*调起微信支付*/
      pay(order_id, user_id, againType, order_no) {
          var that = this;
          wx.login({
              success: res => {
                  http.request({
                      url: api.gotoPreOrder,
                      method: "POST",
                      data: {
                          // uid: user_id,
                          // oid: order_id
                          order_no: order_no,
                      },
                      header: {
                          'content-type': 'application/x-www-form-urlencoded',
                      },
                      success: function(res) {
                          //后端返回的数据
                          console.log('res支付', res)
                          let data = res.data;
                          that.doWxPay(data, againType);
                      },
                      fail: function(err) {
                          wx.showToast({
                              title: "服务器异常，清稍候再试"
                          });
                      }
                  });
              }
          });
      },
      doWxPay(param, againType) {
          let that = this
              //小程序发起微信支付
          wx.requestPayment({
              timeStamp: param.data.timeStamp, //timeStamp是字符串类型的，秒
              nonceStr: param.data.nonceStr,
              package: param.data.package,
              signType: "md5",
              paySign: param.data.paySign,
              success: function(event) {
                  wx.redirectTo({
                      url: `/pages/paySuccess/paySuccess?againType=${againType}`,
                      success: function() {
                          console.log('支付完成跳转！！！', event)

                      }
                  })
              },
              fail: function(error) {
                  wx.showToast({
                      title: '支付取消',
                      icon: 'none',
                      duration: 1500,
                      mask: true,
                      success: function() {
                          console.log('支付取消跳转！！！', error)
                          setTimeout(function() {
                              wx.reLaunch({
                                  url: '/pages/myAllOrderList/myAllOrderList'
                              })
                          }, 2000);
                      }
                  });
              },
              complete: function() {
                  // complete
              }
          });
      },


      onShow: function(options) {
          this.setData({
              showModel: false
          })
          var address = wx.getStorageSync("address") || [];
          if (address.length == 0) {
              var that = this;
              let qqmapsdk = new QQMapWX({
                  key: "OI5BZ-G3FWJ-A6VFG-FGA5U-AZHAT-2NBVY"
              });
              wx.getLocation({
                  type: "wgs84",
                  success(res) {
                      const latitude = res.latitude;
                      const longitude = res.longitude;
                      const speed = res.speed;
                      const accuracy = res.accuracy;
                      qqmapsdk.reverseGeocoder({
                          location: {
                              latitude,
                              longitude
                          },
                          success(res) {
                              console.log(res)
                              that.setData({
                                  address: res.result.address_component.street
                              });
                          }
                      });
                  }
              });
          } else {
              var detail = address.detail || ""
              console.log(wx.getStorageSync("address"))
              if (detail) {
                  this.setData({
                      address: address.address,
                      detail,
                      name: address.name,
                      phone: address.phone
                  })
              } else {
                  this.setData({
                      address: address.address,
                      detail: false
                  })
              }
          }
      },


      onUnload: function() {
          wx.removeStorageSync('myCook')
          wx.removeStorageSync('recommendSelectedItem')
          wx.removeStorageSync('localItem')
      },


  })